<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangxl12.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":true},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":false,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="本文代码取自李沐的《动手学习深度学习》，里面有些代码细节让我觉得非常值得斟酌，特记录。">
<meta property="og:type" content="article">
<meta property="og:title" content="线性回归从零开始实现">
<meta property="og:url" content="https://wangxl12.github.io/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/index.html">
<meta property="og:site_name" content="WXL&#39;s blog">
<meta property="og:description" content="本文代码取自李沐的《动手学习深度学习》，里面有些代码细节让我觉得非常值得斟酌，特记录。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wangxl12.github.io/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/%E6%95%B0%E6%8D%AE%E9%9B%86%E5%8F%AF%E8%A7%86%E5%8C%96.png">
<meta property="article:published_time" content="2021-10-25T02:04:59.000Z">
<meta property="article:modified_time" content="2021-11-23T07:37:29.551Z">
<meta property="article:author" content="WXL">
<meta property="article:tag" content="深度学习">
<meta property="article:tag" content="torch">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wangxl12.github.io/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/%E6%95%B0%E6%8D%AE%E9%9B%86%E5%8F%AF%E8%A7%86%E5%8C%96.png">

<link rel="canonical" href="https://wangxl12.github.io/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>线性回归从零开始实现 | WXL's blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="WXL's blog" type="application/atom+xml">
<link href="https://cdn.bootcss.com/KaTeX/0.11.1/katex.min.css" rel="stylesheet" /></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">WXL's blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Talk is cheap, show me your work.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">33</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">49</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/wangxl12" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangxl12.github.io/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/td.jpg">
      <meta itemprop="name" content="WXL">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="WXL's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          线性回归从零开始实现
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-10-25 10:04:59" itemprop="dateCreated datePublished" datetime="2021-10-25T10:04:59+08:00">2021-10-25</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-23 15:37:29" itemprop="dateModified" datetime="2021-11-23T15:37:29+08:00">2021-11-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index"><span itemprop="name">深度学习</span></a>
                </span>
            </span>

          
            <span id="/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/" class="post-meta-item leancloud_visitors" data-flag-title="线性回归从零开始实现" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>本文代码取自李沐的《动手学习深度学习》，里面有些代码细节让我觉得非常值得斟酌，特记录。</p>
<span id="more"></span>
<h1>生成、可视化数据集</h1>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> utils <span class="keyword">import</span> d2l</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">synthetic_data</span>(<span class="params">w, b, num_examples</span>):</span> </span><br><span class="line">    <span class="string">&quot;&quot;&quot;生成 y = Xw + b + 噪声。&quot;&quot;&quot;</span></span><br><span class="line">    <span class="comment"># 为x添加均值为0，方差为1的正态噪声</span></span><br><span class="line">    X = torch.normal(<span class="number">0</span>, <span class="number">1</span>, (num_examples, <span class="built_in">len</span>(w)))</span><br><span class="line">    y = torch.matmul(X, w) + b</span><br><span class="line">    <span class="comment"># 为y添加均值为0，方差为0.01的正态噪声</span></span><br><span class="line">    y += torch.normal(<span class="number">0</span>, <span class="number">0.01</span>, y.shape)</span><br><span class="line">    <span class="keyword">return</span> X, y.reshape((-<span class="number">1</span>, <span class="number">1</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># true_w和true_b都是真实的w、b，现在根据两参数</span></span><br><span class="line"><span class="comment"># 添加噪声来构建数据集</span></span><br><span class="line">true_w = torch.tensor([<span class="number">2</span>, -<span class="number">3.4</span>])</span><br><span class="line">true_b = <span class="number">4.2</span></span><br><span class="line">features, labels = synthetic_data(true_w, true_b, <span class="number">1000</span>)</span><br><span class="line">d2l.set_figsize()</span><br><span class="line">d2l.plt.scatter(features[:, (<span class="number">1</span>)].detach().numpy(), labels.detach().numpy(), <span class="number">1</span>)</span><br><span class="line">d2l.plt.show()</span><br></pre></td></tr></table></figure>
<p><img src="/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/%E6%95%B0%E6%8D%AE%E9%9B%86%E5%8F%AF%E8%A7%86%E5%8C%96.png" alt="数据集可视化"></p>
<h1>读取数据</h1>
<p>使用迭代器生成数据集</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">data_iter</span>(<span class="params">batch_size, features, labels</span>):</span></span><br><span class="line">    num_examples = features.shape[<span class="number">0</span>]</span><br><span class="line">    indices = <span class="built_in">list</span>(<span class="built_in">range</span>(num_examples))</span><br><span class="line">    <span class="comment"># 打乱样本序号</span></span><br><span class="line">    random.shuffle(indices)</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, num_examples, batch_size):</span><br><span class="line">        <span class="comment"># 从随机数表indices中抽取batch_size个数，</span></span><br><span class="line">        <span class="comment"># 然后将这几个数传入features中</span></span><br><span class="line">        <span class="comment"># 在保证抽取的数量为batch_size的前提下，达到随机挑选样本的目的</span></span><br><span class="line">        batch_indices = torch.tensor(</span><br><span class="line">            indices[i: <span class="built_in">min</span>(i + batch_size, num_examples)]</span><br><span class="line">        )</span><br><span class="line">        <span class="keyword">yield</span> features[batch_indices], labels[batch_indices]</span><br></pre></td></tr></table></figure>
<p>这里有一个问题，即如果样本数量不能整除batch_size，就导致有一些样本始终取不到，为了防止这个问题发生，可以每一次取完之后重新打乱样本序号。</p>
<p>从中取出一个样本数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">batch_size = <span class="number">10</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> X, Y <span class="keyword">in</span> data_iter(batch_size, features, labels):</span><br><span class="line">    <span class="built_in">print</span>(X, <span class="string">&quot;\n&quot;</span>, Y)</span><br><span class="line">    <span class="keyword">break</span></span><br></pre></td></tr></table></figure>
<h1>初始化模型参数</h1>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">w = torch.normal(<span class="number">0</span>, <span class="number">0.01</span>, size=(<span class="number">2</span>, <span class="number">1</span>), requires_grad=<span class="literal">True</span>)</span><br><span class="line"><span class="comment"># w = torch.zeros((2, 1), requires_grad=True)</span></span><br><span class="line">b = torch.zeros(<span class="number">1</span>, requires_grad=<span class="literal">True</span>)</span><br><span class="line"><span class="built_in">print</span>(w)</span><br><span class="line"><span class="built_in">print</span>(b)</span><br></pre></td></tr></table></figure>
<h1>定义模型/损失函数/优化算法</h1>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">linreg</span>(<span class="params">X, w, b</span>):</span></span><br><span class="line">    <span class="keyword">return</span> torch.mm(X, w) + b</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">squared_loss</span>(<span class="params">y_hat, y</span>):</span>  <span class="comment">#@save</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;均方损失。&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">return</span> (y_hat - y.reshape(y_hat.shape)) ** <span class="number">2</span> / <span class="number">2</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sgd</span>(<span class="params">params, lr, batch_size</span>):</span></span><br><span class="line">    <span class="keyword">with</span> torch.no_grad():  </span><br><span class="line">        <span class="keyword">for</span> param <span class="keyword">in</span> params:</span><br><span class="line">            param -= lr * param.grad / batch_size </span><br><span class="line">            <span class="comment"># 当前的梯度只是上一次epoch计算出来的梯度</span></span><br><span class="line">            <span class="comment"># 更新权重之后需要消掉这次梯度，防止和下一次的梯度叠加</span></span><br><span class="line">            <span class="comment"># 下一次的梯度只能从下一次的epoch中计算而来</span></span><br><span class="line">            param.grad.zero_()</span><br></pre></td></tr></table></figure>
<p>这里的sgd函数有几个问题：</p>
<ol>
<li>
<p>为什么这里需要加一个with torch.no_grad()？</p>
<p>因为w和b的requires_grad是True，所有关于他们的运算都会自动构建计算图（用于累积梯度），这里不需要构建静态图、跟踪计算日志，因为我们需要的、和w，b有关的计算图应该仅仅是正向传播的计算图，如果这里不加限制，会自动创建关于权重更新运算的计算图。可以将存储梯度的内存节省下来，这样也可以让代码执行速度更快。</p>
</li>
<li>
<p>这里如何更新权重的，问答区有两个回复非常好，需要记录一下</p>
<blockquote>
<p>当某一变量var在函数外面已经声明时 （如var=v0），函数内部默认var为全局变量且可以访问该变量，除非在函数内部有修改变量var的行为（如重新赋值 var=v1 或者代数运算 var=var+v1 等）。在这种修改变量的情况下，变量var会被定义为局部变量并被重新分配内存，它在函数内部的变化不会影响到外部的全局变量var的值（即var=v0保持不变）。</p>
<p>特殊之处在于本节sgd中使用的运算符（-=）会执行原地操作（in-place operation），也就是运算结果会赋给同一块内存。由于params本身就是全局变量，修改后的结果仍然赋给它的内存，所以变化的也就是全局变量了。如修改为 param = param - … 结果就不对了</p>
</blockquote>
<blockquote>
<p>造成你困惑的最主要原因的核心是“可变对象与不可变对象”。<br>
对于函数中的for循环，param得到的是列表中元素的引用，这没有问题。<br>
但是呢，会不会就地改变（直接作用到变量）这得看具体的实现。<br>
“-=”操作符会调用__isub__函数，而&quot;-&quot;操作符会调用__sub__函数，一般对于可变对象来说“-=”操作符会直接改变self自身。对于pytorch来说，应该会调用sub_函数.</p>
<p>举个例子</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> torch</span><br><span class="line"></span><br><span class="line">x1 = <span class="number">1</span></span><br><span class="line">x2 = <span class="number">2</span></span><br><span class="line">params = [x1, x2]</span><br><span class="line"><span class="keyword">for</span> p <span class="keyword">in</span> params:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">id</span>(p), <span class="built_in">id</span>(x1), <span class="built_in">id</span>(x2))</span><br><span class="line">    p -= <span class="number">4</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">id</span>(p), <span class="built_in">id</span>(x1), <span class="built_in">id</span>(x2))</span><br><span class="line"><span class="built_in">print</span>(params)</span><br><span class="line"></span><br><span class="line">x1 = torch.Tensor([<span class="number">1</span>])</span><br><span class="line">x2 = torch.Tensor([<span class="number">2</span>])</span><br><span class="line">params = [x1, x2]</span><br><span class="line"><span class="keyword">for</span> p <span class="keyword">in</span> params:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">id</span>(p), <span class="built_in">id</span>(x1), <span class="built_in">id</span>(x2))</span><br><span class="line">    p -= <span class="number">4</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">id</span>(p), <span class="built_in">id</span>(x1), <span class="built_in">id</span>(x2))</span><br><span class="line"><span class="built_in">print</span>(params)</span><br></pre></td></tr></table></figure>
<p>你会得到(你自己运行的话，id得到的地址会不一样)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">9784896</span> <span class="number">9784896</span> <span class="number">9784928</span></span><br><span class="line"><span class="number">9784768</span> <span class="number">9784896</span> <span class="number">9784928</span></span><br><span class="line"><span class="number">9784928</span> <span class="number">9784896</span> <span class="number">9784928</span></span><br><span class="line"><span class="number">9784800</span> <span class="number">9784896</span> <span class="number">9784928</span></span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>]</span><br><span class="line"><span class="number">139752445458112</span> <span class="number">139752445458112</span> <span class="number">139752445458176</span></span><br><span class="line"><span class="number">139752445458112</span> <span class="number">139752445458112</span> <span class="number">139752445458176</span></span><br><span class="line"><span class="number">139752445458176</span> <span class="number">139752445458112</span> <span class="number">139752445458176</span></span><br><span class="line"><span class="number">139752445458176</span> <span class="number">139752445458112</span> <span class="number">139752445458176</span></span><br><span class="line">[tensor([-<span class="number">3.</span>]), tensor([-<span class="number">2.</span>])]</span><br></pre></td></tr></table></figure>
<p>可以看到对于int类型，地址变换了，而torch类型，地址却没有变化。<br>
p -= 4等价于p.sub_(4)。这个可变对象改变了自身。而若如vin100提到的写成p = p - 4则会调用构造函数，并返回一个新的变量，也就不可能作用到原先的“可变对象”。<br>
int类没有发生就地变化是因为它是一个不可变对象。</p>
</blockquote>
<p>从两条评论来看，能让权重顺利更新的原因有两个：（1）python函数形参地址和实参地址相同；（2）传入的列表中的元素是tensor(可变对象)。</p>
<p>首先第（1）条保证了函数内外的列表对应的地址一致，如下测试代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">1</span>, <span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span>(<span class="params">a</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;函数内：id(a[0]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">0</span>])&#125;</span>&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&quot;函数外：id(a[0]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">0</span>])&#125;</span>&quot;</span>)</span><br><span class="line">f(a)</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">函数外：<span class="built_in">id</span>(a) = <span class="number">1875349520968</span></span><br><span class="line">函数内：<span class="built_in">id</span>(a) = <span class="number">1875349520968</span></span><br></pre></td></tr></table></figure>
<p>如果对列表中的第一个元素改变一下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">1</span>, <span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span>(<span class="params">a</span>):</span></span><br><span class="line">    a[<span class="number">0</span>] -= <span class="number">1</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;函数内：id(a[0]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">0</span>])&#125;</span>&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&quot;函数外：id(a[0]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">0</span>])&#125;</span>&quot;</span>)</span><br><span class="line">f(a)</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">函数外：<span class="built_in">id</span>(a[<span class="number">0</span>]) = <span class="number">140713631654288</span></span><br><span class="line">函数内：<span class="built_in">id</span>(a[<span class="number">0</span>]) = <span class="number">140713631654256</span></span><br></pre></td></tr></table></figure>
<p>不可变对象（int）的地址发生了变化。</p>
<p>如果改变的是列表里的列表呢（可变对象）？</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">1</span>, <span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span>(<span class="params">a</span>):</span></span><br><span class="line">    a[<span class="number">2</span>][<span class="number">0</span>] -= <span class="number">1</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;函数内：id(a[2]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">2</span>])&#125;</span>&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&quot;函数外：id(a[2]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">2</span>])&#125;</span>&quot;</span>)</span><br><span class="line">f(a)</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">函数外：<span class="built_in">id</span>(a[<span class="number">2</span>]) = <span class="number">1875349520456</span></span><br><span class="line">函数内：<span class="built_in">id</span>(a[<span class="number">2</span>]) = <span class="number">1875349520456</span></span><br></pre></td></tr></table></figure>
<p>发现可变对象的地址没有发生变化。</p>
<p>将列表里的元素全部换成tensor测试一下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">1</span>, <span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]</span><br><span class="line">a = [torch.tensor(elem) <span class="keyword">for</span> elem <span class="keyword">in</span> a]</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span>(<span class="params">a</span>):</span></span><br><span class="line">    a[<span class="number">0</span>] -= <span class="number">1</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;函数内：id(a[0]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">0</span>])&#125;</span>&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&quot;函数外：id(a[0]) = <span class="subst">&#123;<span class="built_in">id</span>(a[<span class="number">0</span>])&#125;</span>&quot;</span>)</span><br><span class="line">f(a)</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">函数外：<span class="built_in">id</span>(a[<span class="number">0</span>]) = <span class="number">1875366498040</span></span><br><span class="line">函数内：<span class="built_in">id</span>(a[<span class="number">0</span>]) = <span class="number">1875366498040</span></span><br></pre></td></tr></table></figure>
<p>地址没有改变，这就印证了上面的说法。</p>
</li>
<li>
<p>这里更新权重，为什么需要除以batch_size</p>
<p>因为所使用的squared_loss损失函数最终没有除以N，得到的并不是平均损失，用这个损失求得的梯度也不是平均梯度，而是所有（batch_size个）样本一并产生的损失所求得的梯度，而我们平常更新权重的时候，使用的是平均损失所计算而来的梯度（平均梯度），如果不除以batch_size可能导致下降的太快（设想一下<code>param -= lr * param.grad / batch_size</code>中<code>param.grad</code>变为原来的<code>batch_size</code>倍），导致进入局部极小值。</p>
</li>
<li>
<p>为什么需要使用grad.zero_()</p>
<p>当前的梯度只是上一次epoch计算出来的梯度，更新权重之后需要消掉这次梯度，防止和下一次的梯度叠加，下一次的梯度只能从下一次的epoch中计算而来。</p>
</li>
<li>
<p>如果我们使用官方的损失函数来代替我们自己实现的损失函数，而且用<code>nn.MSELoss(reduction=‘sum’)</code>替换 <code>nn.MSELoss（）</code>为了使代码的行为相同，需要怎么更改学习速率？为什么？</p>
<p>​	参考官方文档中，这个函数的实现细节：<a target="_blank" rel="noopener" href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html">https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html</a></p>
<p>​	应该把学习率除以batch_size，因为默认参数是’mean’，换成’sum’需要除以批量数，一般会采用默认，因为这样学习率可以跟batch_size解耦。我们测试一下，修改前：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">loss = nn.MSELoss()</span><br><span class="line">trainer = torch.optim.SGD(net.parameters(), lr=<span class="number">0.03</span>)</span><br><span class="line"></span><br><span class="line">num_epochs = <span class="number">3</span></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(num_epochs):</span><br><span class="line">    <span class="keyword">for</span> X, y <span class="keyword">in</span> data_iter:</span><br><span class="line">        l = loss(net(X), y)</span><br><span class="line">        <span class="comment"># 这里和前面自己实现的不同</span></span><br><span class="line">        <span class="comment"># 这个API没有自动清零梯度</span></span><br><span class="line">        <span class="comment"># 需要利用传入优化算法的API来手动清零</span></span><br><span class="line">        trainer.zero_grad()</span><br><span class="line">        l.backward()</span><br><span class="line">        <span class="comment"># 优化过程：</span></span><br><span class="line">        trainer.step()</span><br><span class="line">    <span class="comment"># 优化完成之后，需要手动计算所有的features和labels之间的损失值</span></span><br><span class="line">    l = loss(net(features), labels)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;epoch <span class="subst">&#123;epoch + <span class="number">1</span>&#125;</span>, loss <span class="subst">&#123;l:f&#125;</span>&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">epoch <span class="number">1</span>, loss <span class="number">0.000103</span></span><br><span class="line">epoch <span class="number">2</span>, loss <span class="number">0.000102</span></span><br><span class="line">epoch <span class="number">3</span>, loss <span class="number">0.000101</span></span><br></pre></td></tr></table></figure>
<p>修改后：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">loss = nn.MSELoss(reduction=<span class="string">&#x27;sum&#x27;</span>)</span><br><span class="line">trainer = torch.optim.SGD(net.parameters(), lr=<span class="number">0.03</span>/batch_size)</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">epoch <span class="number">1</span>, loss <span class="number">0.102505</span></span><br><span class="line">epoch <span class="number">2</span>, loss <span class="number">0.101427</span></span><br><span class="line">epoch <span class="number">3</span>, loss <span class="number">0.101685</span></span><br></pre></td></tr></table></figure>
<p>发现取sum的损失值显著大于默认的mean损失值，为什么？</p>
<p>mean意味着所有样本损失的平均值，即loss会除以样本数，sum没有除这个样本数，所以会放大1000倍（这里样本数为1000），可以试着将样本数改成10000，会发现两种方式确实损失值相差1w倍。</p>
</li>
</ol>
<h1>训练</h1>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">lr = <span class="number">0.03</span></span><br><span class="line">num_epochs = <span class="number">3</span></span><br><span class="line">net = linreg</span><br><span class="line">loss = squared_loss</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(num_epochs):</span><br><span class="line">    <span class="keyword">for</span> X, y, <span class="keyword">in</span> data_iter(batch_size, features, labels):</span><br><span class="line">        l = loss(net(X, w, b), y) <span class="comment"># X和Y的小批量损失</span></span><br><span class="line">        <span class="comment"># 因为l的形状是（batch_size, 1)，而不是一个标量，&#x27;l&#x27;中所有元素被加到一起来计算梯度</span></span><br><span class="line">        l.<span class="built_in">sum</span>().backward()</span><br><span class="line">        sgd([w, b], lr, batch_size) <span class="comment"># 使用参数的梯度进行更新</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 在经过一个epoch更新之后，重新计算此时的预测损失值为多少</span></span><br><span class="line">    <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">        train_l = loss(net(features, w, b), labels)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">f&#x27;epoch <span class="subst">&#123;epoch + <span class="number">1</span>&#125;</span>, loss <span class="subst">&#123;<span class="built_in">float</span>(train_l.mean())&#125;</span>&#x27;</span>)</span><br><span class="line">    </span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&#x27;w的估计误差: <span class="subst">&#123;true_w - w.reshape(true_w.shape)&#125;</span>&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&#x27;b的估计误差: <span class="subst">&#123;true_b - b&#125;</span>&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>训练的基本步骤是进行多个epoch，每一个epoch都会将所有的数据遍历一遍，但是每一次遍历不是一次性将所有的数据加载入内存，而是使用迭代器的方式多个batch加载。</p>
<p>加载完数据需要投入模型计算，计算估计值和真实值之间的损失函数，利用损失函数进行反向传播，从而计算需要优化的参数的梯度。</p>
<p>使用参数的梯度更新参数，更新完成之后计算此时预测的结果和真实值之间的损失值并输出。</p>
<p>反复执行上述步骤，直至退出循环。</p>
<p><strong>有两个问题</strong>：</p>
<ol>
<li>
<p>为什么需要计算得到损失值，然后才对进行更新，而不是直接根据表达式更新，因为我觉得参数的梯度和损失值无关，而是求偏导之后和X有关。</p>
<p>有这个疑问其实是对于pytorch的静态图没有理解，凡是有关于grad needed变量的运算，pytorch都会记录其操作符，并构建反向传播图，如果不计算loss，那么这一步构建反向传播图就无法进行，求偏导确实和损失值本身无关。</p>
</li>
<li>
<p>为什么每一次计算一个batch的损失之后，就需要马上进行反向传播，我可否将每一个batch计算得到的损失拼接起来，最后进行更新？或者每一个batch都更新一次，然后将损失值拼接起来，后面每个batch都会将以前的batch的损失值拼接起来一起更新权重？</p>
<p>​	首先说第一种，基于这一思想，改写代码逻辑如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">lr = <span class="number">0.03</span></span><br><span class="line">num_epochs = <span class="number">300</span></span><br><span class="line">net = linreg</span><br><span class="line">loss = squared_loss</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(num_epochs):</span><br><span class="line">    count = <span class="number">1</span></span><br><span class="line">    l = <span class="literal">None</span></span><br><span class="line">    <span class="keyword">for</span> X, y, <span class="keyword">in</span> data_iter(batch_size, features, labels):</span><br><span class="line">        count += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> l <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            l = loss(net(X, w, b), y) <span class="comment"># X和Y的小批量损失</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            torch.cat((l, loss(net(X, w, b), y)), dim=<span class="number">0</span>)</span><br><span class="line">    <span class="comment"># 退出循环之后（遍历所有样本之后）反向传播，然后更新权重</span></span><br><span class="line">    l.<span class="built_in">sum</span>().backward()</span><br><span class="line">    sgd([w, b], lr, batch_size * count) </span><br><span class="line">    </span><br><span class="line">    <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">        train_l = loss(net(features, w, b), labels)</span><br><span class="line">        <span class="keyword">if</span> (epoch + <span class="number">1</span>) % <span class="number">10</span> == <span class="number">0</span>: </span><br><span class="line">            <span class="built_in">print</span>(<span class="string">f&#x27;epoch <span class="subst">&#123;epoch + <span class="number">1</span>&#125;</span>, loss <span class="subst">&#123;<span class="built_in">float</span>(train_l.mean())&#125;</span>&#x27;</span>)</span><br><span class="line">    </span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&#x27;w的估计误差: <span class="subst">&#123;true_w - w.reshape(true_w.shape)&#125;</span>&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&#x27;b的估计误差: <span class="subst">&#123;true_b - b&#125;</span>&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>最终效果并不好，最终更新的次数就是epoch次，首先次数大大减少，如果增加epoch数量，之前样本数是1000，batch_size是10，epoch是3，一共会更新300次，所以直接将epoch设置为300进行测试，将最后5个epoch计算得到的损失值列出来：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">epoch <span class="number">260</span>, loss <span class="number">13.599431037902832</span></span><br><span class="line">epoch <span class="number">270</span>, loss <span class="number">13.525508880615234</span></span><br><span class="line">epoch <span class="number">280</span>, loss <span class="number">13.450084686279297</span></span><br><span class="line">epoch <span class="number">290</span>, loss <span class="number">13.36327838897705</span></span><br><span class="line">epoch <span class="number">300</span>, loss <span class="number">13.275373458862305</span></span><br><span class="line">w的估计误差: tensor([ <span class="number">1.7403</span>, -<span class="number">2.9753</span>], grad_fn=&lt;SubBackward0&gt;)</span><br><span class="line">b的估计误差: tensor([<span class="number">3.6783</span>], grad_fn=&lt;RsubBackward1&gt;)</span><br></pre></td></tr></table></figure>
<p>效果还是很差，损失值下降非常缓慢。</p>
<p>第二种思路行不通，首先根据这种思路改写代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">lr = <span class="number">0.03</span></span><br><span class="line">num_epochs = <span class="number">3000</span></span><br><span class="line">net = linreg</span><br><span class="line">loss = squared_loss</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(num_epochs):</span><br><span class="line">    count = <span class="number">1</span></span><br><span class="line">    l = <span class="literal">None</span></span><br><span class="line">    <span class="keyword">for</span> X, y, <span class="keyword">in</span> data_iter(batch_size, features, labels):</span><br><span class="line">        count += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> l <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            l = loss(net(X, w, b), y) <span class="comment"># X和Y的小批量损失</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            torch.cat((l, loss(net(X, w, b), y)), dim=<span class="number">0</span>)</span><br><span class="line">        <span class="comment"># 将前一次的损失cat过来一起反向传播，然后更新权重</span></span><br><span class="line">        l.<span class="built_in">sum</span>().backward()</span><br><span class="line">        sgd([w, b], lr, batch_size * count) </span><br><span class="line">    </span><br><span class="line">    <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">        train_l = loss(net(features, w, b), labels)</span><br><span class="line">        <span class="keyword">if</span> (epoch + <span class="number">1</span>) % <span class="number">10</span> == <span class="number">0</span>: </span><br><span class="line">            <span class="built_in">print</span>(<span class="string">f&#x27;epoch <span class="subst">&#123;epoch + <span class="number">1</span>&#125;</span>, loss <span class="subst">&#123;<span class="built_in">float</span>(train_l.mean())&#125;</span>&#x27;</span>)</span><br><span class="line">    </span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&#x27;w的估计误差: <span class="subst">&#123;true_w - w.reshape(true_w.shape)&#125;</span>&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&#x27;b的估计误差: <span class="subst">&#123;true_b - b&#125;</span>&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>代码执行会报错：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">RuntimeError: Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=<span class="literal">True</span> when calling backward the first time.</span><br></pre></td></tr></table></figure>
<p>因为每一次正向传播的过程中，在requires_grad=True的情况下会构建反向梯度计算图，在反向传播之后都会释放掉，因为模型过大时一直占用很容易爆内存，释放之后下一个循环就无法计算被释放部分的变量的梯度。</p>
</li>
</ol>

    </div>

    
    
    
        <div class="reward-container">
  <div>行行好，赏一杯咖啡吧~</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.jpg" alt="WXL 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpg" alt="WXL 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>WXL
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wangxl12.github.io/2021/10/25/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%9E%E7%8E%B0/" title="线性回归从零开始实现">https://wangxl12.github.io/2021/10/25/深度学习/线性回归从零开始实现/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/" rel="tag"><i class="fa fa-tag"></i> 深度学习</a>
              <a href="/tags/torch/" rel="tag"><i class="fa fa-tag"></i> torch</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/24/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/pytorch%E7%9A%84%E8%87%AA%E5%8A%A8%E6%B1%82%E5%AF%BC/" rel="prev" title="pytorch的自动求导">
      <i class="fa fa-chevron-left"></i> pytorch的自动求导
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/10/29/GNN/%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5/" rel="next" title="基本概念">
      基本概念 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">1.</span> <span class="nav-text">生成、可视化数据集</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">2.</span> <span class="nav-text">读取数据</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">3.</span> <span class="nav-text">初始化模型参数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">4.</span> <span class="nav-text">定义模型&#x2F;损失函数&#x2F;优化算法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">5.</span> <span class="nav-text">训练</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="WXL"
      src="/images/td.jpg">
  <p class="site-author-name" itemprop="name">WXL</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">49</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">33</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/wangxl12" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wangxl12" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wxl.1.2.3@qq.com" title="E-Mail → mailto:wxl.1.2.3@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://blog.csdn.net/weixin_43141320?spm=1000.2115.3001.5343" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;weixin_43141320?spm&#x3D;1000.2115.3001.5343" rel="noopener" target="_blank">My CSDN Blog</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://blog.kilig.ink/" title="http:&#x2F;&#x2F;blog.kilig.ink&#x2F;" rel="noopener" target="_blank">HuangPiSong</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">WXL</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>


  <script defer src="/lib/three/three.min.js"></script>
    <script defer src="/lib/three/three-waves.min.js"></script>


  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 's5o4gRGNyYbPVRfziI5EzhO1-gzGzoHsz',
      appKey     : 'N7aQtR2SU9AwgaO2YtVhRO0W',
      placeholder: "发表你的评论吧~",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : true,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
